package com.umakr.ax.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 *
 * @author ~scl
 * @date 2017/5/5
 */
public class FileUploadUtil {

    private FileUploadUtil() {
        throw new IllegalStateException("FileUploadUtil class");
    }
    /**
     *
     * @param file
     * @param uploadDir
     * @return
     */
    public static String fileUpload(MultipartFile file, String uploadDir){
        String uploadFilePath = "";

        if(!file.isEmpty()){

            File uploadDirPath = new File(uploadDir);
            if(!uploadDirPath.exists()){
                uploadDirPath.mkdirs();
            }

            String newFilePath = uploadDir + File.separator+file.getOriginalFilename();

            //是否需要重命名 如果不需要重命名则需要判断该文件是否存在或者根据时间戳来限定文件夹
            File checkFile = new File(newFilePath);
            try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(checkFile))){
                out.write(file.getBytes());
                out.flush();
                uploadFilePath = newFilePath;
            } catch (Exception e) {
                uploadFilePath = "对不起，文件上传失败";
            }
        }else{
            uploadFilePath = "对不起，不能上传空文件";
        }
       return uploadFilePath;
    }

}
